/*
 * m406_tester.c
 *
 * Created: 27.02.2013 12:38:24
 *  Author: saenko
 */ 


#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>
#include <avr/pgmspace.h>

#include "uart.h"
#include "SPI.h"
#include "ad5291.h"
#include "ADC.h"
#include "1w.h"
#include "ds18b20.h"

uint8_t tmpr_ok;
uint8_t adc_buf[8];
uint8_t adc_ch;
uint8_t out_ready_flag;
uint8_t temp_8;
uint16_t temp_16;

int main(void)
{
	spi_init();
	uart_init();
	ADC_init();
	OW_init();
	sei();
	
	//printstr_p(PSTR("ATMega88 OK\n"));
	ad5291_init();
	
	
    while(1)
    {
        if(uart_flags.rxstring_end)
		{
			uart_flags.rxstring_end = 0;			
			
			switch(rxstring[0])
			{

			case 'C':

					temp_16 = read_ctrl_reg();
					temp_8 = temp_16;
					putchr(temp_8);
					temp_16 = temp_16 >> 8;
					temp_8 = temp_16;
					putchr(temp_8);
			break;	
			
						case 'R':

						temp_16 = ad5291_read_RDAC();
						temp_8 = temp_16;
						putchr(temp_8);
						temp_16 = temp_16 >> 8;
						temp_8 = temp_16;
						putchr(temp_8);
						break;
			
			case 'V':
					temp_16 = rxstring[1];
					temp_16 = temp_16 << 8;
					temp_16 = temp_16 + rxstring[2];
					if(temp_16<1024) ad5291_set_vol(temp_16);		
			break;
			
			case 'I':
					ad5291_init();
			break;
			
						case 'B':
						ad5291_set_vol(0x00AB);
						break;
			}
			

			
			

		}
		
					
			if(ADC_flag_complete)
			{
				ADC_flag_complete = 0;
				
				switch(adc_ch)
				{
				case 6: 
						adc_buf[6] = ADC_data;
						adc_ch = 7;
				break;
				case 7: 
						adc_buf[7] = ADC_data;
						adc_ch = 6;
						
						tmpr_ok = get_temperature();						
						
						out_ready_flag = 1;
				break;
				default: adc_ch = 6; break;
				}
	
			    ADC_start(adc_ch);								
		
			}
			
			if(out_ready_flag)
			{
				out_ready_flag = 0;
				
								putchr('A');
								putchr('S');
								putchr(adc_buf[6]);
								putchr(tmpr_ok);
								putchr(scratch_buf[0]);
								putchr(scratch_buf[1]);
								putchr(scratch_buf[6]);
								putchr(scratch_buf[7]);
								putchr(adc_buf[7]);
								
			}

		
    }
	
	

}